package com.skivingcloud.admin.security;

import com.skivingcloud.admin.constants.Constant;
import com.skivingcloud.admin.sys.entity.SysUser;
import com.skivingcloud.admin.sys.service.SysUserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author hushouquan
 */
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService, UserDetailsPasswordService{
    private final SysUserService sysUserService;

    public MyUserDetailsServiceImpl(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword){
        return null;
    }
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        SysUser user = sysUserService.loadUserByName(username);
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<String> premList = sysUserService.getUserPermissions(user.getId());
        SecurityUser securityUser = new SecurityUser();
        securityUser.setId(user.getId());
        securityUser.setUsername(user.getUsername());
        securityUser.setPassword(user.getPassword());
        securityUser.setEnabled(Constant.USER_STATUS_NORMAL.equals(user.getStatus()));
        securityUser.setAccountNonLocked(!Constant.USER_STATUS_LOCKED.equals(user.getStatus()));
        securityUser.setAccountNonExpired(!Constant.COMMON_STATUS_DELETED.equals(user.getStatus()));
        securityUser.setCredentialsNonExpired(true);
        securityUser.setTenantId(user.getTenantId());
        securityUser.setStaffName(user.getStaffName());
        securityUser.setPrems(premList);
        return securityUser;
    }
}
